package com.muqi.app.qlearn.login;

import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.TextView;

import com.muqi.app.network.http.MyAsyncHttp;
import com.muqi.app.network.http.NetWorkUtils;
import com.muqi.app.network.http.ParamsUtils;
import com.muqi.app.network.http.MyAsyncHttp.AsyncCallBackListener;
import com.muqi.app.network.http.MyAsyncHttp.RESULTCODE;
import com.muqi.app.project.contants.MContants;
import com.muqi.app.project.contants.NetWorkApi;
import com.muqi.app.project.utils.AppUtils;
import com.muqi.app.project.utils.ShowToast;
import com.muqi.app.qlearn.student.BaseFragmentActivity;
import com.muqi.app.qlearn.student.R;
import com.muqi.app.qlearn.student.ui.AddChildActivity;

public class RegistActivity extends BaseFragmentActivity implements
		OnClickListener, OnCheckedChangeListener {
	private EditText phone_number;
	private EditText check_code;
	private EditText password;
	private EditText repassword;
	private Button btn_register;

	// private ImageButton show_pwd;
	private TextView get_check_code;
	private TextView look_protocal;
	private CheckBox checkbox;
	private String strPhone_number;
	private String strPassword;
	private String strRePassword;
	private String strCheckcode;
	private String confirm_code = "";
	protected boolean isShowpwd = true;
	private int type = 1;
	private boolean isAgree = true;
	private CountDownTimer timer = new CountDownTimer(60000, 1000) {

		@Override
		public void onTick(long millisUntilFinished) {
			get_check_code.setEnabled(false);
			get_check_code.setText((millisUntilFinished / 1000) + "秒后重发");
		}

		@Override
		public void onFinish() {
			get_check_code.setEnabled(true);
			get_check_code.setText("重新获取");
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.aty_register);
	}

	@Override
	protected void onInit() {
		phone_number = (EditText) findViewById(R.id.phone_number);
		check_code = (EditText) findViewById(R.id.check_code_input);
		password = (EditText) findViewById(R.id.password_input);
		repassword = (EditText) findViewById(R.id.confirm_input);
		checkbox = (CheckBox) findViewById(R.id.agrre_deal);
		look_protocal = (TextView) findViewById(R.id.look_protocal);
		look_protocal.setOnClickListener(this);
		btn_register = (Button) findViewById(R.id.btn_register_now);
		btn_register.setOnClickListener(this);
		get_check_code = (TextView) findViewById(R.id.get_check_code);
		get_check_code.setOnClickListener(this);
		// show_pwd = (ImageButton)findViewById(R.id.show_pwd);
		// show_pwd.setOnClickListener(this);
		checkbox.setOnCheckedChangeListener(this);
	}

	@Override
	protected void onData() {
		// TODO Auto-generated method stub
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_register_now:
			strPhone_number = phone_number.getText().toString().trim();
			strPassword = password.getText().toString().trim();
			strRePassword = repassword.getText().toString().trim();// 获取输入的确认密码
			strCheckcode = check_code.getText().toString().trim();
			if (checkInput(type)) {
				registerAccount();
			}
			break;
		case R.id.get_check_code:
			strPhone_number = phone_number.getText().toString().trim();
			if (TextUtils.isEmpty(strPhone_number)) {
				phone_number.setError(getString(R.string.phone_empty));
			} else if (!AppUtils.checkPhone(strPhone_number)) {
				phone_number.setError("手机号输入不正确");
			} else {
				getCheckcode();
			}
			break;
		case R.id.look_protocal:// 点击查看协议

			break;
		/*
		 * case R.id.show_pwd: if(isShowpwd){
		 * password.setTransformationMethod(HideReturnsTransformationMethod
		 * .getInstance());
		 * repassword.setTransformationMethod(HideReturnsTransformationMethod
		 * .getInstance()); isShowpwd = false; }else{
		 * password.setTransformationMethod
		 * (PasswordTransformationMethod.getInstance());
		 * repassword.setTransformationMethod
		 * (PasswordTransformationMethod.getInstance()); isShowpwd = true; }
		 * break;
		 */
		default:
			break;
		}
	}

	/**
	 * 注册
	 */
	public void registerAccount() {
		if (NetWorkUtils.isNetworkAvailable(this)) {
			showProgressWithState("正在注册...");
			HashMap<String, Object> register = new HashMap<String, Object>();
			register.put("user_type", "parents");
			register.put("mobile", strPhone_number);
			register.put("password", strPassword);
			String requestUrl = ParamsUtils.buildParams(
					NetWorkApi.Register_Api, register);
			MyAsyncHttp.get(this, requestUrl, new AsyncCallBackListener() {

				@Override
				public void onAsyncCallBack(RESULTCODE resuleCode,
						String request, String result) {
					Log.e("===", result);
					if (resuleCode == RESULTCODE.SUCCESS) {
						showSuccessWithState();
						try {
							JSONObject resultJson = new JSONObject(result);
							JSONObject dataJson = resultJson
									.getJSONObject("data");
							mSpUtil.setToken(dataJson.getString("token"));
							mSpUtil.setUserId(dataJson.getString("id"));
							mSpUtil.setUserType(MContants.LOGIN_AS_PARENTS);
							startActivityForResult(new Intent(mContext,
									AddChildActivity.class), 10010);

						} catch (JSONException e) {
							e.printStackTrace();
							showErrorWithState();
						}
					} else {
						hidingSVloading();
						showToast(result);
					}
				}
			});
		} else {
			ShowToast.showShort(this, R.string.net_break);// 提示无网络
		}
	}

	/**
	 * 获取验证码
	 */
	public void getCheckcode() {
		if (NetWorkUtils.isNetworkAvailable(this)) {
			timer.start();
			HashMap<String, Object> register = new HashMap<String, Object>();
			register.put("mobile", strPhone_number);
			String requestUrl = ParamsUtils.buildParams(
					NetWorkApi.CheckCode_Api, register);
			MyAsyncHttp.get(this, requestUrl, new AsyncCallBackListener() {

				@Override
				public void onAsyncCallBack(RESULTCODE resuleCode,
						String request, String result) {
					if (resuleCode == RESULTCODE.SUCCESS) {
						try {
							JSONObject resultJson = new JSONObject(result);
							confirm_code = resultJson.getString("data");
							//check_code.setText(confirm_code);
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				}
			});
		} else {
			ShowToast.showShort(this, R.string.net_break);// 提示无网络
		}
	}

	/**
	 * 检测用户名和密码
	 * 
	 * @return
	 */
	private boolean checkInput(int type) {
		switch (type) {
		case 1:
			if (TextUtils.isEmpty(strPhone_number)) {
				phone_number.setError(getString(R.string.phone_empty));
				return false;
			} else if (!AppUtils.checkPhone(strPhone_number)) {
				phone_number.setError("手机号输入不正确");
				return false;
			}
			// 验证码非空验证
			else if (TextUtils.isEmpty(strCheckcode)) {
				check_code.setError(getString(R.string.checkcode_empty));
				return false;
			}
			// 验证码正确性验证
			else if (!confirm_code.equals(strCheckcode)) {
				check_code.setError(getString(R.string.checkcode_wrong));
				return false;
			} else if (!isAgree) {
				showToast("请先同意注册协议");
				return false;
			}
			break;
		case 2:
			if (TextUtils.isEmpty(strPhone_number)) {
				phone_number.setError("邮箱不能为空");
				return false;
			} else if (!AppUtils.checkEmail(strPhone_number)) {
				phone_number.setError("邮箱输入不正确");
				return false;
			}
			break;
		}

		if (TextUtils.isEmpty(strPassword)) {
			password.setError(getString(R.string.login_password_empty));
		} else if (strPassword.trim().length() < 6) {
			password.setError(getString(R.string.password_length_alert));
		}
		// 验证输入的确认密码
		else if (TextUtils.isEmpty(strRePassword)) {
			repassword.setError(getString(R.string.register_repassword_empty));
		}
		// 判断是否勾选同意协议的复选框
		else if (!checkbox.isChecked()) {
			ShowToast.showShort(this, R.string.agree_protocol);
		}
		// 判断两次密码是否输入一致
		else if (!strPassword.equals(strRePassword)) {
			repassword.setError(getString(R.string.password_different));
		} else {
			return true;
		}
		return false;
	}

	public void onBack(View v) {
		this.finish();
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		isAgree = isChecked;
	}

	@Override
	protected void onActivityResult(int arg0, int arg1, Intent arg2) {
		// TODO Auto-generated method stub
		super.onActivityResult(arg0, arg1, arg2);
		if (arg0 == 10010) {
			startActivity(LoginActivity.class);
			finish();
		}
	}
}
